package dshop.service;

import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;

/**
 * 缓存服务
 */
public class RedisService {

	/**
	 * 缓存客户端授权信息
	 * <br>登录成功时使用
	 */
	public static void cacheApiAuth(String token, Integer userId,String userPhone)
	{
		clearApiAuth(userId);
		
		Redis.use().set(token, userId);
		Redis.use().set("api_login_" + userId, token);
		Redis.use().set("api_user_phone_" + userId, userPhone);
	}
	
	/**
	 * 读取客户端用户ID
	 * <br>用于验证登录状态
	 */
	public static int getApiUserId(String token)
	{
		Object value = Redis.use().get(token);
		if (value == null) 
		{
			return -1;
		}
		return (Integer)value;
	}
	/**
	 * 读取操作人手机
	 * <br>用于验证登录状态
	 */
	public static String getApiUserPhone(Integer userId)
	{
		Object value = Redis.use().get("api_user_phone_" + userId);
		if (value == null) 
		{
			return "";
		}
		return (String)value;
	}
	
	/**
	 * 清除客户端登录信息
	 * <br>退出登录调用
	 */
	public static void clearApiAuth(Integer userId)
	{
		if (userId == null || userId < 0) 
		{
			return;
		}
		String token = Redis.use().get("api_login_" + userId);
		if (token != null) 
		{
			Redis.use().del(token);
		}
		Redis.use().del("api_login_" + userId);
		Redis.use().del("api_user_phone_" + userId);
	}
	
	public static String cacheWeixinStateValue(String state)
	{
		String key = "weixin_" + System.currentTimeMillis();
		Cache cache = Redis.use();
		cache.setex(key, 120, state);
		return key;
	}
	
	public static String getWeixinStateValue(String key)
	{
		Cache cache = Redis.use();
		Object obj = cache.get(key);
		return obj == null ? null : (String)obj;
	}
}
